package com.shopping.commons;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shopping.dao.CarDao;
import com.shopping.dao.FlowerDao;
import com.shopping.dao.impl.CarDaoImpl;
import com.shopping.dao.impl.FlowerDaoImpl;
import com.shopping.model.Car;
import com.shopping.model.Flower;
import com.shopping.model.Flower;
import com.shopping.model.view.CarView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UnLoginCar
 * @Description: TODO
 * @Author: JiaShiXi
 * @Date: 2021/3/21 12:41
 * @Version: 1.0
 **/

public class LoginUtil {
    /**
     * 将Car集合转换为CarView集合
     *
     * @param carList
     * @return
     */
    public static List<CarView> UnLoginCarTransfer(List<Car> carList) {
        FlowerDao flowerDao = new FlowerDaoImpl();
        List<CarView> carViewList = new ArrayList<>();
        for (Car car : carList) {
            CarView carView = new CarView();
            Flower flower = flowerDao.queryFlowerDesc(car.getFlower_id());
            carView.setCar_count(car.getCar_count());
            carView.setFlower_id(car.getFlower_id());
            carView.setFlower_image(flower.getFlower_image());
            carView.setFlower_name(flower.getFlower_name());
            carView.setFlower_price(flower.getFlower_price());
            carView.setSum_price(flower.getFlower_price() * car.getCar_count());
            carViewList.add(carView);
        }
        return carViewList;
    }

    /**
     * 添加缓存中购物车信息到数据库中,并将缓存中的购物车信息删除
     *
     * @param user_id
     * @param cookies
     * @param response
     * @throws UnsupportedEncodingException
     */
    public static void addCacheCar(Integer user_id, Cookie[] cookies, HttpServletResponse response) throws UnsupportedEncodingException {
        CarDao carDao = new CarDaoImpl();

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("shopCart")) { //cookie中如果存在购物车信息

                //将购物车的Json字符串解码为utf-8格式
                String jsonStr = URLDecoder.decode(cookie.getValue(), "utf-8");

                //将购物车Json字符串转换为List集合
                List<Car> carList = JSONObject.parseArray(jsonStr, Car.class);


                for (Car car : carList) {
                    //将当前用户的ID添加到每个购物车的对象中
                    car.setUserId(user_id);
//                    System.out.println(user_id);
//                    System.out.println(car.getFlower_id());
                    //改:如果购物车中有该商品，则更新该商品
                    boolean isContains = carDao.isContains(car.getFlower_id(),user_id);
                    System.out.println(car.getFlower_id()+":"+isContains);
                    if (isContains){ //没有该商品
                        //调用添加购物车的方法
                        carDao.addCar(car);
                    }else { //有该商品

                        Integer count = carDao.getCountByUserIdAndFlowerId(user_id, car.getFlower_id());
//                        System.out.println("原来购物车中的数量"+count);
                        Integer car_count_cache = car.getCar_count();
//                        System.out.println("缓存中购物车中的数量"+car_count_cache);
                        carDao.updateCount(car.getFlower_id(),user_id,car_count_cache);
                    }
                }

                //清除购物车信息的cookie
                cookie.setMaxAge(0);

                //将最新的cookie添加到响应中
                response.addCookie(cookie);
            }
        }
    }

    /**
     * 未登录情况下，添加购物车
     *
     * @param cookies 当前request中获取到的所有的Cookie数组
     * @param flowerId  花卉ID
     * @return 购物车的Cookie对象
     * @throws UnsupportedEncodingException
     */
    public static Cookie unLoginAddCar(Cookie[] cookies, Integer flowerId) throws UnsupportedEncodingException {

        //定义一个存放购物车信息的Json字符串
        String jsonStr = null;

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("shopCart")) { //有购物车的Cookie
                    //获取存放在cookie中的购物车信息的Json字符串
                    jsonStr = URLDecoder.decode(cookie.getValue(), "utf-8");
                }
            }
        }

        //新建一个存放商品对象的集合
        ArrayList<Car> shopList = new ArrayList<>();

        if (jsonStr == null) { //无购物车的Cookie，此时购物车中一件商品也没有

            //实例化一个购物车对象，将花卉ID和数量封装进去
            Car car = new Car();
            car.setFlower_id(flowerId);
            car.setCar_count(1);

            //将购物车对象添加到集合中
            shopList.add(car);

        } else { //购物车中有数据

            //将购物车的Json字符串解析为Json
            List<Car> carList = JSONObject.parseArray(jsonStr, Car.class);

            //商品是否以及存在购物车
            boolean isExist = false;

            for (Car car : carList) { //循环购物车已有的商品

                Integer flower_id = car.getFlower_id();
                Integer car_count = car.getCar_count();

                if (flower_id == flowerId){ //如果添加的是之前添加过的商品
                    isExist = true; //已存在标志设为true
                    car.setCar_count(++car_count); //将当前商品的数量加1
                }

                //添加到集合中
                shopList.add(car);
            }

            if (!isExist) { //当前商品之前没有添加过
                //添加新商品
                Car car = new Car();
                car.setFlower_id(flowerId);
                car.setCar_count(1);
                shopList.add(car);
            }
        }

        //将商品集合转为Json字符串格式
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(shopList));
        String jsonDataStr = jsonArray.toJSONString();

        //存入cookie
        Cookie shopCartCookie = new Cookie("shopCart", URLEncoder.encode(jsonDataStr, "utf-8"));
        shopCartCookie.setPath("/");
        shopCartCookie.setMaxAge(60 * 60 * 24 * 7);

        return shopCartCookie;
    }

}
